package com.lambkit.dao.record;

import cn.hutool.core.util.StrUtil;
import com.jfinal.plugin.activerecord.DbKit;
import com.lambkit.dao.model.LambkitModel;
import com.lambkit.db.LambkitTableMapping;
import com.lambkit.db.TableMappingManager;

import java.util.function.Function;

public class LambkitApiServiceImpl<M extends LambkitRecord> extends BaseLambkitApiService<M> {

	//jfinal configName
	protected String configName;
	//para class
	protected Class<M> pojoClass;
	// table name
	protected String tableName;
	// primary key
	protected String primaryKey;
	
	public void init(Class<M> lambkitRecordClass, String configName) {
		this.pojoClass = lambkitRecordClass;
		this.configName = configName;
		String cname = StrUtil.isNotBlank(this.configName) ? this.configName : DbKit.MAIN_CONFIG_NAME;
		LambkitTableMapping tableMapping = TableMappingManager.me().getPojoMapping(cname, lambkitRecordClass);
		if(tableMapping!=null) {
			String tableName = tableMapping.getTableName();
			String pkName = tableMapping.getPrimaryKey();
			if(StrUtil.isNotBlank(configName)) {
				mapping(configName, tableName, pkName);
			} else {
				mapping(tableName, pkName);
			}
		}
	}
	
	//-----------------------------
	//-----------------------------

	public void mapping(LambkitModel model) {
		this.configName = model.configName();
		this.tableName = model.tableName();
	}

	public void mapping(String configName, String tableName, String primaryKey) {
		this.configName = configName;
		this.tableName = tableName;
		this.primaryKey = primaryKey;
	}

	public void mapping(String tableName, String primaryKey) {
		this.tableName = tableName;
		this.primaryKey = primaryKey;
	}

	@Override
	public String getConfigName() {
		return configName;
	}

	@Override
	public String getTableName() {
		return tableName;
	}

	@Override
	public String getPrimaryKeyName() {
		return primaryKey;
	}

	@Override
	public Class<M> getLambkitRecordClass() {
		return pojoClass;
	}

	@Override
	public Function<M, Boolean> getFunction(Function<M, Boolean> func) {
		return func != null ? func : null;
	}

	public void setLambkitPojoClass(Class<M> clazz) {
		this.pojoClass = clazz;
	}
}
